package SpLib.display
{
	import flash.geom.Point;
	
	public class MoveHelper
	{
		public static const NOMOVE:String = "NoMove";
		public static const MOVEDONE:String = "MoveDone";
		
		public static const DIRECT_LEFT:String = "Left";
		public static const DIRECT_RIGHT:String = "Right";
		public static const DIRECT_UP:String = "Up";
		public static const DIRECT_DOWN:String = "Down";
		public static const DIRECT_LEFT_UP:String = "Left_Up";
		public static const DIRECT_LEFT_DOWN:String = "Left_Down";
		public static const DIRECT_RIGHT_UP:String = "Right_Up";
		public static const DIRECT_RIGHT_DOWN:String = "Right_Down";
		
		private var m_DestPos:Point = null;
		private var m_nSpeed:Number;
		private var m_MoveOff:Point;
		private var m_Pos:Point;
		
		static public function GetAngel(x0:Number,y0:Number,px:Number,py:Number):Number
		{
			return Math.atan2( py - y0, px - x0);
		}
		
		static public function GetDirect(angel:Number):String
		{		
			if(Math.abs(angel)<=(Math.PI/8)) return DIRECT_RIGHT;
			if(Math.abs(angel)>=(Math.PI*7/8)) return DIRECT_LEFT;
			if(angel<(-Math.PI*3/8) && angel>(-Math.PI*5/8)) return DIRECT_UP;
			if(angel>(Math.PI*3/8) && angel<(Math.PI*5/8)) return DIRECT_DOWN;
			
			if(angel>(Math.PI/8) && angel<(Math.PI*3/8)) return DIRECT_RIGHT_DOWN;
			if(angel<(-Math.PI/8) && angel>(-Math.PI*3/8)) return DIRECT_RIGHT_UP;
			
			if(angel>(Math.PI*5/8)) return DIRECT_LEFT_DOWN;
			if(angel<(-Math.PI*5/8)) return DIRECT_LEFT_UP;
		
			return NOMOVE;
		}
		
		static public function GetMoveStep(angel:Number,speed:Number):Point
		{
			var dp:Point = new Point;
			dp.x = Math.cos(angel)*speed;
			dp.y = Math.sin(angel)*speed;
			return dp;
		}
		
		public function MoveHelper()
		{
		}
		
		public function get pos():Point
		{
			return m_Pos;
		}
		
		public function get destpos():Point
		{
			return m_DestPos;
		}
		
		public function Move(curpos:Point,dest:Point,speed:Number):String
		{
			m_Pos = curpos.clone();
			m_MoveOff = curpos.clone();
			m_nSpeed = speed;
			m_DestPos = dest.clone();
			
			var a:Number = GetAngel(m_MoveOff.x,m_MoveOff.y,m_DestPos.x,m_DestPos.y);
			return GetDirect(a);
		}
		
		public function MoveStep():String
		{
			if(m_DestPos==null)
			{
				return NOMOVE;
			}
			
			var dis:Number = Point.distance(m_DestPos,m_MoveOff);
			if(dis<m_nSpeed)
			{
				m_MoveOff = m_DestPos.clone();
				m_Pos = m_DestPos.clone();
				m_DestPos = null;
				return MOVEDONE;
			}
			
			var a:Number = GetAngel(m_MoveOff.x,m_MoveOff.y,m_DestPos.x,m_DestPos.y);
			var offset:Point = GetMoveStep(a,m_nSpeed);
			
			m_MoveOff.x += offset.x;
			m_MoveOff.y += offset.y;
			
			var dx:int = m_MoveOff.x - m_Pos.x;
			var dy:int = m_MoveOff.y - m_Pos.y;
			
			if(Math.abs(dx)>=1 || Math.abs(dy)>=1)
			{
				m_Pos.x += dx;
				m_Pos.y += dy;
				return GetDirect(a);
			}
			
			return NOMOVE;
		}
	}
}